package com.hzf.booklibrary.utils;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 *图片加载工具类
 */
public class ImageLoadUtils {
    public static class ImageSize{
        int height;
        int width;
    }
    /**
     * 根据ImageView获适当的压缩的宽和高
     *
     * @param imageView
     * @return
     */
    @SuppressLint("NewApi")
    public  ImageSize getImageViewSize(ImageView imageView){
        ImageSize imageSize = new ImageSize();
        DisplayMetrics displayMetrics = imageView.getContext().getResources().getDisplayMetrics();
        ViewGroup.LayoutParams lp = imageView.getLayoutParams();
        int width = imageView.getWidth();// 获取imageview的实际宽度
        if(width<=0){
            width=lp.width;// 获取imageview在layout中声明的宽度
        }
        if(width<0){
            // width = imageView.getMaxWidth();// 检查最大值
            width=imageView.getMaxWidth();
        }
        if(width<=0){
            width=displayMetrics.widthPixels;
        }
        int height = imageView.getHeight();// 获取imageview的实际高度
        if (height <= 0)
        {
            height = lp.height;// 获取imageview在layout中声明的宽度
        }
        if (height <= 0)
        {
            height = imageView.getMaxHeight();// 检查最大值
        }
        if (height <= 0)
        {
            height = displayMetrics.heightPixels;
        }
        imageSize.width=width;
        imageSize.height=height;
        return imageSize;
    }

    /**
     * 根据ImageView的宽高压缩本地图片
     * @param path
     * @return
     */
    public  Bitmap compressBitmapFromLocal(String path, int width,int height){
        // 获得图片的宽和高，并不把图片加载到内存中
        BitmapFactory.Options options = new  BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        BitmapFactory.decodeFile(path,options);
        options.inSampleSize=caculateInSampleSize(options,width,height);
        // 使用获得到的InSampleSize再次解析图片
        options.inJustDecodeBounds = false;
        options.inInputShareable = true;
        options.inPurgeable = true;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        return bitmap;
    }
    /**
     * 从本地获取图片
     * @param path
     * @param imageView
     * @return
     */
    public  Bitmap loadImageFromLocal(String path,ImageView imageView){
        Bitmap bm;
        ImageSize imageSize = getImageViewSize(imageView);
        bm = compressBitmapFromLocal(path,imageSize.width,imageSize.height);
        return bm;
    }

    /**
     * 从网络中获取图片并压缩
     * @param urlStr
     * @param imageView
     * @return
     */
    public  Bitmap downloadImgByUrl(String urlStr,ImageView imageView){
        ByteArrayOutputStream baos = null;
        InputStream is=null;
        try {
            //路径空格问题 --防止服务器端返回505(替换空格)
            urlStr = urlStr.replaceAll(" ", "%20");

            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            int responseCode = conn.getResponseCode();
            if(responseCode!=200){
                return null;
            }
            is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            byte [] bytes = new byte[1024];
            int temp=0;
            //把流写入baos
            while ((temp=is.read(bytes))!=-1){
                baos.write(bytes,0,temp);
            }
            is.close();
            baos.close();
            //数据放到数组中
            byte[] data = baos.toByteArray();
//            BitmapFactory.Options opts = new BitmapFactory.Options();
//            opts.inJustDecodeBounds=true;
//            Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length,opts);
////          注：decodeStream会使Input读流的时候mark标记失效
////          Bitmap bitmap = BitmapFactory.decodeStream(is,null,opts);
//
//            ImageSize imageSize =getImageViewSize(imageView);
//            opts.inSampleSize=caculateInSampleSize(opts,imageSize.width,imageSize.height);
//
//            opts.inJustDecodeBounds=false;
//            Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length,opts);
            BitmapFactory.Options options = new  BitmapFactory.Options();
//            options.inJustDecodeBounds =true;
//            Bitmap bm = BitmapFactory.decodeByteArray(data,0,data.length,options);
              ImageSize imageSize = getImageViewSize(imageView);
//            options.inSampleSize = caculateInSampleSize(options,imageSize.width,imageSize.height);
//            options.inJustDecodeBounds=false;

            options.inInputShareable = true;
            options.inPurgeable = true;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length,options);
            //bitmap=compressImage(bitmap);
            //将图片显示为固定大小，但是会出现伸缩效果
//            bitmap = Bitmap.createScaledBitmap(bitmap,imageSize.width,imageSize.height,false);
            conn.disconnect();
            return bitmap;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据需求的宽和高以及图片实际的宽和高计算SampleSize
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public  int caculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight ){
        int width = options.outWidth;
        int height = options.outHeight;
        int inSampleSize = 1;
        if(width>reqWidth||height>reqHeight){
            int widthRadio = Math.round(width*1.0f/reqWidth);
            int heightRadio = Math.round(height*1.0f/reqHeight);
            inSampleSize=Math.max(widthRadio,heightRadio);
        }
        return inSampleSize;
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;

        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        image.recycle();//回收图片
        return bitmap;
    }
}
